package com.zyw.security.shiro.web.realm;

import com.zyw.security.shiro.web.authc.AuthInfo;
import com.zyw.security.shiro.web.authc.AuthService;
import com.zyw.security.shiro.web.authc.tk.WeixinQYAuthcToken;
import org.apache.shiro.authc.*;

/**
 * @author zhangyw
 * @date 2018/1/24 11:18
 */
public class WeixinQYAuthRealm extends BasicAuthRealm {

    public WeixinQYAuthRealm() {
        this.setName("sky_sso_weixin_qy_realm");
        this.setAuthenticationTokenClass(WeixinQYAuthcToken.class);
    }

    public WeixinQYAuthRealm(AuthService authService) {
        this();
        this.setAuthService(authService);
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        WeixinQYAuthcToken weixinQYToken = (WeixinQYAuthcToken) token;

        if (!getAuthService().validCredentials((String) weixinQYToken.getPrincipal(), (String) weixinQYToken.getCredentials(), null)) {
            throw new AccountException("微信企业state验证失败");
        }

        AuthInfo authInfo = getAuthService().getAuthInfo(weixinQYToken.getPrincipal());

        if (authInfo == null){
            throw new AccountException("账户不存在");
        }

        return new SimpleAuthenticationInfo(authInfo, weixinQYToken.getState(), getName());
    }
}
